const {
  render
} = require('ejs');
const { json } = require('express');
var express = require('express');
var router = express.Router();

//加载数据库配置文件
let db = require("../model/db");

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', {
    title: 'Express'
  });
});
//首页数据接口
router.get("/index", async (req, res) => {
  //查询数据库中的数据
  let sql = `select * from stu_username`;
  let [err, data] = await db.query(sql);
  //console.log(data);
  if (err) {
    res.send({
      "code": 400,
      "msg": "查询数据失败"
    })
  } else {
    // 将数据库中的数据存储起来
    res.cookie("dt",data);
    res.send({
      "code": 200,
      "msg": "查询数据成功",
      "data": data
    })
  }
})

router.post("/add", async (req, res) => {
  //接收前端数据
  let dat = req.body
  dat = JSON.parse(dat.data)
  let {name,sex,age,qq} = dat;
  let u = req.cookies.dt.findIndex((item)=>{
    console.log(item.qqemail,qq);
    return item.qqemail == qq
  })
  // 判断数据库中是否有相同的qq邮箱
  if(u == -1){
    let sql = `insert into stu_username (name,sex,age,qqemail) value ("${name}","${sex}",${age},"${qq}")`;
    let [err, data] = await db.query(sql);
    res.send({ "code": "200", "msg": "该邮箱可以注册" });
  }else{
    res.send({ "code": "400", "msg": "该邮箱已被注册" });
  }
})

module.exports = router;